#!/bin/sh
xtrabackup=xtrabackup
xtrabackupFULL=/usr/bin/$xtrabackup
TODAY=`date +%Y%m%d%H%M`
YESTERDAY=`date -d"yesterday" +%Y%m%d%H%M`
USEROPTIONS="--user=root --password=root123 --socket=/var/lib/mysql/mysql.sock"
TMPFILE="/tmp/innobackup_$TODAY.$$.tmp"
MYCNF=/etc/my.cnf
MYSQL=/tmp/mysql/bin/mysql
MYSQLADMIN=/tmp/mysql/bin/mysqladmin
BACKUPDIR=/tmp/xtra_backup # 备份的主目录
FULLBACKUPDIR=$BACKUPDIR/full # 全库备份的目录
# Grab start time
#############################################################################
# Display error message and exit
#############################################################################
error()
{
   echo "$1" 1>&2
   exit 1
}
# Check options before proceeding
if [ ! -x $xtrabackupFULL ]; then
 error "$xtrabackupFULL does not exist."
fi
if [ ! -d $BACKUPDIR ]; then
 error "Backup destination folder: $BACKUPDIR does not exist."
fi
if [ -z "`$MYSQLADMIN $USEROPTIONS status | grep 'Uptime'`" ] ; then
error "HALTED: MySQL does not appear to be running."
fi
if ! `echo 'exit' | $MYSQL -s $USEROPTIONS` ; then
error "HALTED: Supplied mysql username or password appears to be incorrect (not copied here for security, see script)."
fi
# Some info output
echo "----------------------------"
echo
echo "$0: MySQL backup script"
echo "started: `date`"
echo
# Create full backup directories if they not exist.
for i in $FULLBACKUPDIR
do
       if [ ! -d $i ]; then
               mkdir -pv $i
       fi
done
# 前一天的备份
echo "压缩前一天的备份"
cd $BACKUPDIR
tar -zcvf $YESTERDAY.tar.gz ./full/
if [ $? = 0 ]; then
 rm -rf $BACKUPDIR/full
 echo "Running new full backup."
 xtrabackup  --defaults-file=$MYCNF $USEROPTIONS --backup --target-dir=$FULLBACKUPDIR > $TMPFILE 2>&1
else
 echo "Error with tar."
fi
if [ -z "`tail -1 $TMPFILE | grep 'completed OK!'`" ] ; then
echo "$xtrabackup  failed:"; echo
echo "---------- ERROR OUTPUT from $xtrabackup  ----------"
# cat $TMPFILE
# rm -f $TMPFILE
exit 1
fi
# 获取本次备份的目录
THISBACKUP=`awk -- "/Backup created in directory/ { split( \\\$0, p, \"'\" ) ; print p[2] }" $TMPFILE`
echo "THISBACKUP=$THISBACKUP"
#rm -f $TMPFILE
echo "Databases backed up successfully to: $THISBACKUP"
# Cleanup
echo "delete tar files of 3 days ago"
find $BACKUPDIR/ -mtime +3 -name "*.tar.gz" -exec rm -rf {} \;
echo
echo "completed: `date`"
exit 0
